package com.joe.mp4_demo.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class FFmepgUtils {

    public static void doFFe(String mp4SavePath){
        long startTime =System.currentTimeMillis();
        List commend = new ArrayList();
        commend.add("D:/ffmpeg-N-103611-gdb2514a5dc-win64-gpl/bin/ffmpeg.exe");
        //以1fps读入
        commend.add("-r");
        commend.add("40");
        //-threads 2 以两个线程进行运行， 加快处理的速度。
        commend.add("-threads");
        commend.add("4");
        commend.add("-f");
        commend.add("image2");
        commend.add("-i");
        commend.add("C:/Users/Administrator/Desktop/baimg/%04d.jpeg");
        commend.add("-vcodec");
        commend.add("libx264");
        //-y 对输出文件进行覆盖
        commend.add("-y");
        //-r 5 fps设置为5帧/秒（不同位置有不同含义)  %2d标识图片文件的正则
        commend.add("-r");
        commend.add("10");
        commend.add(mp4SavePath);
        start(commend);
        long endTime =System.currentTimeMillis();
        System.out.println("视频生成耗时："+(endTime-startTime));
    }

    public static void start(List commend) {
        Process p = null;
        try {
            ProcessBuilder builder = new ProcessBuilder(commend);
            builder.command(commend);
            p = builder.start();
            p.getOutputStream().close();
            doWaitFor(p);
            p.destroy();
        } catch (Exception e) {
            log.info("异常信息:{}",e);
            p.destroy();
        }
    }

    public static int doWaitFor(Process p) {
        InputStream in = null;
        InputStream err = null;
        int exitValue = -1;

        try {
            in = p.getInputStream();
            err = p.getErrorStream();
            boolean finished = false;

            while(!finished) {
                try {
                    Character c;
                    while(in.available() > 0) {
                        c = new Character((char)in.read());
                        System.out.print(c);
                    }

                    while(err.available() > 0) {
                        c = new Character((char)err.read());
                        System.out.print(c);
                    }

                    exitValue = p.exitValue();
                    finished = true;
                } catch (IllegalThreadStateException var19) {
                    Thread.currentThread();
                    Thread.sleep(500L);
                }
            }
        } catch (Exception var20) {
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException var18) {
            }

            if (err != null) {
                try {
                    err.close();
                } catch (IOException var17) {
                }
            }

        }

        return exitValue;
    }
}
